<?php
/**
 * Created by 2019/4/13 0013
 * Effect: TokenValidationMiddleware.php
 * Author: 品花
 * Date: 2019/4/13 0013
 * Time: 上午 10:37
 */

namespace Middleware;


use Consts\RedisKey;
use Helper\Config;
use Helper\Output;
use Helper\Mysql;
use Helper\Redis;
use Helper\Reg;

class CustomerMiddleware
{
    protected static $instance;

    public static function getInstance()
    {
        if ( !isset(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    public function online($customer_id,$fd){

        try {
            $old_fd = Redis::getInstance()->hGet(RedisKey::WS_CUSTOMER_FD_TO_UID,$customer_id);
            if($old_fd){
                //挤掉线
                Reg::getInstance()->get('server')->disconnect($old_fd);
            }
            //进行fd和uid绑定
            Redis::getInstance()->hSet(RedisKey::WS_CUSTOMER_FD_TO_UID, $fd,$customer_id);
            Redis::getInstance()->hSet(RedisKey::WS_CUSTOMER_UID_TO_FD, $customer_id,$fd);
        }catch (\Exception $e){

            var_dump($e->getMessage());
        }



    }

    public function offline($fd){

        $uid = Redis::getInstance()->hGet(RedisKey::WS_CUSTOMER_FD_TO_UID,$fd);
        Redis::getInstance()->hDel(RedisKey::WS_CUSTOMER_FD_TO_UID,$fd);
        Redis::getInstance()->hDel(RedisKey::WS_CUSTOMER_UID_TO_FD,$uid);
        Redis::getInstance()->hDel(RedisKey::CUSTOMER_NOW_SESS_IP ,'uid:'.$uid );
        \Swoole\Timer::after(16*1000,function ()use ($uid){

            var_dump('16秒未重连！移除排队');
            //移除队列
            $auid = Redis::getInstance()->hGet(RedisKey::CUSTOMER_BIND_SERVICE,'uid:'.$uid);
//            var_dump('auid',$auid);
//            var_dump('uid',$uid);
            if($auid){
                Redis::getInstance()->zRem(RedisKey::service_queue_list($auid),$uid);
                Redis::getInstance()->hDel(RedisKey::CUSTOMER_BIND_SERVICE,'uid:'.$uid);
            }


        });

    }


}

